package com.heba.fragment.search;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.search.FeatureSearchListObject;
import com.heba.bean.search.FeatureSearchObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.fragment.LazyFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.scan.ItemFeatureActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 特点搜寻
 * Created by jason on 2020/9/26.
 */
public class SearchFeatureFragment extends LazyFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;
    private View viewNoData;

    private String searchContent;

    private List<FeatureSearchObject> searchList;

    private FeatureSearchListObject searchListObject;

    /**
     * 实例化fragment
     * 接收参数
     *
     * @param searchContent
     * @return
     */
    public static SearchFeatureFragment newInstance(String searchContent) {
        SearchFeatureFragment fragment = new SearchFeatureFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.SEARCH_CONTENT, searchContent);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        searchContent = bundle.getString(CommonConfig.SEARCH_CONTENT, "");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_scan_search_recyclerview, container, false);
        parseArgument();
        initView(view);
        return view;
    }

    @Override
    protected void lazyLoad() {
        getFeatureData();
    }

    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);
        viewNoData = view.findViewById(R.id.view_no_data);

        searchList = new ArrayList<>();

        recycleAdapter = new QuickAdapter<FeatureSearchObject>(searchList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_feature_search;
            }

            @Override
            public void convert(VH holder, FeatureSearchObject data, int position) {
                TextView tvTitle = holder.getView(R.id.tv_title);
                View viewFeature = holder.getView(R.id.view_feature);
                TextView tvFeature = holder.getView(R.id.tv_feature);
                ImageView ivPhoto = holder.getView(R.id.iv_photo);
                ImageView ivClose = holder.getView(R.id.iv_close);

                tvTitle.setVisibility(View.GONE);
                viewFeature.setVisibility(View.GONE);
                ivClose.setVisibility(View.GONE);

                switch (data.getType()) {
                    case FeatureSearchObject.TYPE_NONE:
                        viewFeature.setVisibility(View.VISIBLE);
                        if (data.getRecentID() != 0) {
                            ivClose.setVisibility(View.VISIBLE);
                        }
                        SpannableString s = CommonUtils.matcherSearchText(getContext(),
                                data.getName(), searchContent);
                        tvFeature.setText(s);
                        GlideUtil.loadImageWithDefaultPlaceHolder(getContext(), data.getIcon(), ivPhoto);
                        break;
                    case FeatureSearchObject.TYPE_RECENT:
                        tvTitle.setVisibility(View.VISIBLE);
                        tvTitle.setText(getResources().getString(R.string.public_recent));
                        break;
                    case FeatureSearchObject.TYPE_POPULAR:
                        tvTitle.setVisibility(View.VISIBLE);
                        tvTitle.setText(data.getTitle());
                        break;
                    default:
                        break;
                }

                /**
                 * 删除记录
                 */
                ivClose.setOnClickListener(v -> new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                    @Override
                    public void onYesClick() {
                        progressDialog.show();
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
                                progressDialog.dismiss();
                                refreshData(searchContent);
                            }

                            @Override
                            public void Fail(String error) {
                                progressDialog.dismiss();
                            }
                        }).handleRecentLog(getContext(), CommonConfig.HANDLER_DELETE, CommonConfig.HANDLE_TYPE_FEATURE, data.getRecentID(), 0);
                    }

                    @Override
                    public void onNoClick() {

                    }
                }).showDialog(getContext(), getResources().getString(R.string.tips), getResources().getString(R.string.confirm_delete)));

                /**
                 * 进去特点页面
                 */
                viewFeature.setOnClickListener(v -> {
                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                        @Override
                        public void Success() {
                            refreshData(searchContent);
                        }

                        @Override
                        public void Fail(String error) {
                        }
                    }).handleRecentLog(getContext(), CommonConfig.HANDLER_ADD, CommonConfig.HANDLE_TYPE_FEATURE, 0, data.getFeatureID());

                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.FEATURE_ID, String.valueOf(data.getFeatureID()));
                    bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, data.getName());
                    openActivity(ItemFeatureActivity.class, bundle);
                });

            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshData(searchContent);
        });
    }

    /**
     * 搜索刷新数据
     *
     * @param content
     */
    public void refreshData(String content) {
        this.searchContent = content;
        getFeatureData();
    }

    /**
     * 获取分类数据
     */
    private void getFeatureData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", 100);
        params.put("Keyword", searchContent);
        client.get(Cfg.BaseUrl + "/Product/KeywordFeature", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            searchListObject = new Gson().fromJson(jsonObject.toString(), FeatureSearchListObject.class);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (!searchList.isEmpty() && searchList.size() > 0)
                            searchList.clear();

                        //最近搜索
                        if (!searchListObject.getRecents().isEmpty()) {
                            FeatureSearchObject object = new FeatureSearchObject();
                            object.setType(FeatureSearchObject.TYPE_RECENT);
                            searchList.add(object);
                            searchList.addAll(searchListObject.getRecents());
                        }

                        //热门搜索
                        if (!searchListObject.getPopulars().isEmpty()) {
                            for (int i = 0; i < searchListObject.getPopulars().size(); i++) {
                                FeatureSearchListObject.FeatureGroupListObject groupListObject = (FeatureSearchListObject.FeatureGroupListObject) searchListObject.getPopulars().get(i);
                                FeatureSearchObject object = new FeatureSearchObject();
                                object.setType(FeatureSearchObject.TYPE_POPULAR);
                                object.setTitle(groupListObject.getName());
                                searchList.add(object);
                                for (int j = 0; j < groupListObject.getLists().size(); j++) {
                                    FeatureSearchObject object1 = groupListObject.getLists().get(j);
                                    searchList.add(object1);
                                }
                            }
                        }

                        //搜索记录列表
                        if (!searchListObject.getSearchs().isEmpty()) {
                            searchList.clear();
                            searchList.addAll(searchListObject.getSearchs());
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();

                        viewNoData.setVisibility(searchList.isEmpty() ? View.VISIBLE : View.GONE);
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }

}
